from streamlit import status
from fastapi import status
from app.extensions import SessionLocal
from app.models.Student import Student
from app.repositories.StudentRepo import StudentRepository
from app.asserts import Codes
from app.repositories.ClasRepo import ClasRepository

class StudentService():
    def __init__(self, db: SessionLocal):
        # 在service创建DAO层对象
        self.repo = StudentRepository(db)
        self.clas_repo = ClasRepository(db)

    def get_by_keyword(self, keyword):
        """
        根据关键字查询数据
        :param keyword: 关键字
        :return:
        """
        data = self.repo.get_by_keyword(keyword)
        return {
            "code": status.HTTP_200_OK,
            "data": data,
            "message": "查询成功"
        }

    def add_student(self, clas_id, name, gender):
        # 检查clas_id存在吗
        clas = self.clas_repo.get_clas_by_id(clas_id)
        if clas is None:
            return {
                "code": Codes.NOT_FOUND,
                "data": None,
                "message": "班级不存在"
            }

        result = self.repo.add_student(int(clas_id), name, gender)
        if result:
            return {
                "code": Codes.SUCESS,
                "data": None,
                "message": "学生创建成功"
            }
        return {
            "code": Codes.SERVICE_ERROR,
            "data": None,
            "message": "学生创建失败"
        }


    def update_student(self, stu_id, new_name, new_gerder, new_clas_id):
        stu = self.repo.get_student_by_id(stu_id,)
        # 增加学生
        if stu is None:
            return {
                "code": Codes.NOT_FOUND,
                "data": None,
                "message": "学生不存在"
            }
        clas = self.clas_repo.get_clas_by_id(new_clas_id)
        if clas is None:
            new_clas_id = ""
        result = self.repo.update_student(stu_id, new_name, new_gerder, new_clas_id)
        if result:
            return {
                "code": Codes.SUCESS,
                "data": None,
                "message": "修改成功"
            }
        return {
            "code": Codes.SERVICE_ERROR,
            "data": None,
            "message": "修改失败"
        }

    def delete_student(self, id):
        #判断学生是否已经存在
        stu = self.repo.get_student_by_id(id)
        if stu is None:
             return {
                 "code": status.HTTP_404_NOT_FOUND,
                 "data": None,
                 "message": "学生不存在"
             }
        result = self.repo.delete_student(id)
        if result:
            return {
                "code": status.HTTP_200_OK,
                "data": None,
                "message": "删除成功"
            }
        else:
            return {
                "code": status.HYYP_500_INTERNAL_SERVER_ERROR,
                "data": None,
                "message": "删除失败"
            }
